const net = require('net');
const JNS = require("./JNSProtocol")
const log4js = require("log4js");
const Log = log4js.getLogger("client");

/**
 * 对原始 Socket Client 封装
 * 直接支持 frame
 * 直接支持 Ping-Pong
 */
class Client extends net.Socket{
    constructor(){
        super();
        this.frame = new JNS();
        this.frame.setRequestHandler( (id, data) =>{
            this.onData && this.onData(JSON.parse(data))
        })

        this.frame.setResponseHandler( (id, data) =>{
            this.onData && this.onData(JSON.parse(data))
        })

        this.frame.setPingHandler( () =>{
            this.write(this.frame.pongPack.data)
        })

        this.frame.setErrorHandler = ( (err,data) =>{
            console.log(err,data)
        })


        this.lastRecvTime = (new Date()).getTime();
        this.timer = setInterval( () =>{
            let now = (new Date()).getTime();
            if(  this.lastRecvTime + 60000 < now ){
                Log.trace("timeout")
                process.exit(-2)
            }

            if(  this.lastRecvTime + 15000 < now ){
                Log.trace("idle  " + (now - this.lastRecvTime))
                this.write(this.frame.pingPack.data)
            }

        }, 15000)
    }

    send(data, type){
        let pack = this.frame.pack(JSON.stringify(data), type);
        this.write(pack.data);
        return pack.id
    }

    on( event , cb ){
        if( "data" == event ){
            super.on("data", (data) => {
                this.lastRecvTime = (new Date()).getTime();
                Log.trace("收到原始数据", this.lastRecvTime)
                this.frame.hook(data);
            })
            this.onData = cb;
        }else{
            super.on(event, cb);
        }
    }
}


module.exports = Client